import { Component } from "react";
import "@/pages/Demo01.css"

class DemoA extends Component {
    constructor(props) {
        super(props)
        this.state = {
            todo: '',
            list: []
        }
    }
    // 获取输入框信息
    getTodo(e) {
        // console.log(e);
        this.setState({ todo: e.target.value })
    }
    // 添加Todo
    addTodo(e) {
        if (!this.state.todo.trim()) {
            alert("输入框没有内容~~")
            return;
        }
        this.setState(state => ({ list: [...state.list, { id: Date.now(), content: state.todo, checked: false }] }))
        this.setState({
            todo: ""
        })
    }
    // 回车添加Todo
    addByEnter(e) {
        // 回车的keyCode是13
        if (e.keyCode == 13) {
            this.addTodo(e)
        }
    }
    // 删除Todo
    delTodo(id) {
        this.setState(state => ({
            list: state.list.filter(item => item.id != id)
        }))
    }
    // 改变Todo checked
    changeChecked(e, id) {
        console.log(e);
        this.setState(state => ({
            list: state.list.map((item) => {
                if (item.id == id) {
                    item.checked = !item.checked
                }
                return item
            })
        }))
    }
    render() {
        let { todo, list } = this.state;
        return (
            <div className="Todo">
                <div className="ipt">
                    <input type="checkbox" />
                    <input className="ptt" type="text" value={todo} onChange={(e) => this.getTodo(e)}
                        onKeyUp={e => this.addByEnter(e)}
                    />
                    <button onClick={(e) => this.addTodo(e)}>添加</button>
                </div>
                <div>
                    {list.map((item, index) => (
                        <div className="TItem" key={item.id}>
                            <input type="checkbox" onClick={e => this.changeChecked(e, item.id)} />
                            <span>{item.content}</span>
                            <button onClick={() => this.delTodo(item.id)}>删除</button>
                        </div>
                    ))}
                </div>
            </div>
        )
    }
}

export default DemoA